<template>
  <div id="tenant-register">
    <a-spin :spinning="isSubmitting" :tip="l('Registering')">
      <h1 class="header">租户注册</h1>
      <a-alert
        :message="l('TenantEncodingsAreNotRepeatable')"
        type="warning"
        show-icon
        style="margin-bottom: 20px"
      />

      <a-form :model="form" @submit="save($event)" :rules="rules" ref="formRef">
        <!-- 租户Code -->
        <a-form-item name="tenancyName">
          <a-input
            v-model:value="form.tenancyName"
            :placeholder="l('TenancyCodeName')"
            autoComplete="“off”"
          >
            <template #prefix><CloudOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input>
        </a-form-item>

        <!-- 租户名称 -->
        <a-form-item name="name">
          <a-input
            v-model:value="form.name"
            :placeholder="l('DisplayTenancyName')"
            autoComplete="“off”"
          >
            <template #prefix><UserOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input>
        </a-form-item>

        <!-- 管理员用户名 -->
        <a-form-item name="userName">
          <a-input
            v-model:value="form.userName"
            :placeholder="l('AdminUserName')"
            autoComplete="“off”"
          >
            <template #prefix><UserOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input>
        </a-form-item>

        <!-- 管理员邮箱 -->
        <a-form-item name="adminEmailAddress">
          <a-input
            v-model:value="form.adminEmailAddress"
            :placeholder="l('AdminEmailAddress')"
            @blur="userNameOrEmailAddressOnBlur()"
            autoComplete="“off”"
            type="email"
          >
            <template #prefix><MailOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input>
        </a-form-item>

        <!-- 管理员密码 -->
        <a-form-item name="tenantAdminPassword">
          <a-input
            v-model:value="form.tenantAdminPassword"
            :placeholder="l('Password')"
            autoComplete="“off”"
            type="password"
          >
            <template #prefix><LockOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input>
        </a-form-item>

        <!-- 验证码 -->
        <a-form-item v-if="useCaptcha" name="verificationCode">
          <captcha
            v-model="form.verificationCode"
            ref="captcha"
            :placeholder="l('CAPTCHA')"
            :primaryKey="primaryKey"
            :type="captchaType"
            @update:modelValue="getChange($event)"
          />
        </a-form-item>

        <a-form-item class="btn--container">
          <a-button type="primary" html-type="submit" block @click="save($event)">
            {{ l('Register') }}
          </a-button>
        </a-form-item>
      </a-form>

      <a-row>
        已有账号？
        <router-link to="/account/login">{{ l('立刻登录') }}</router-link>
      </a-row>
    </a-spin>
  </div>
</template>

<script lang="ts">
  import { TenantRegistrationServiceProxy, CreateTenantDto } from '/@/shared/service-proxies';
  import { AppComponentBase } from '/@/shared/component-base';
  import { Captcha } from '../components';
  import { loginService } from '../login/login.service';
  import { CloudOutlined, UserOutlined, LockOutlined, MailOutlined } from '@ant-design/icons-vue';
  import { defineComponent } from 'vue';

  function hasErrors(fieldsError) {
    return Object.keys(fieldsError).some((field) => fieldsError[field]);
  }
  export default defineComponent({
    name: 'TenantRegister',
    components: {
      Captcha,
      CloudOutlined,
      UserOutlined,
      LockOutlined,
      MailOutlined,
    },
    mixins: [AppComponentBase],
    //  name: 'tenant-register',
    data() {
      return {
        hasErrors,
        isSubmitting: false, // 提交中
        tmpPrimaryKey: 'undefined',
        verificationImgUrl: undefined, // 验证码地址
        form: new CreateTenantDto(),
        loginService: loginService,
        tenantRegistrationServiceProxy: new TenantRegistrationServiceProxy(),
        rules: {
          tenancyName: [
            {
              required: true,
              message: this.l('TheTenantCodeCannotBeEmpty'),
              trigger: 'blur',
            },
            {
              min: 3,
              message: this.l('MinLength', 3),
              trigger: 'blur',
            },
            {
              pattern: '^[a-zA-Z][a-zA-Z0-9_-]{1,}$',
              message: this.l(
                'OnlyNumbersAndLettersCanBeEnteredAndTheFirstCharacterCannotBeANumber',
              ),
              trigger: 'blur',
            },
          ],
          name: [
            {
              required: true,
              message: this.l('TheTenantDisplayNameCannotBeEmpty'),
            },
            {
              max: 32,
              message: this.l('MaxLength', 32),
            },
          ],
          userName: [
            {
              required: true,
              message: this.l('TheAdministratorUserNameCannotBeEmpty'),
            },
            {
              max: 32,
              message: this.l('MaxLength', 32),
            },
          ],
          adminEmailAddress: [
            {
              required: true,
              message: this.l('AdministratorMailboxesCannotBeEmpty'),
            },
            {
              pattern: '^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$',
              message: this.l('NotEmail'),
              trigger: 'blur',
            },
          ],
          tenantAdminPassword: [
            {
              required: true,
              message: this.l('ThePasswordCannotBeEmpty'),
            },
          ],
          verificationCode: [{ required: true, message: this.l('ThisFieldIsRequired') }],
        },
      };
    },
    computed: {
      primaryKey: {
        get: function () {
          return this.tmpPrimaryKey;
        },
        set: function (value: any) {
          if (value === null) return;
          this.tmpPrimaryKey = value;
        },
      },
      captchaType() {
        // 验证码类型
        if (this.appSession.tenantId) {
          return this.appConsts.settings.HostSettings.UseCaptchaOnTenantRegistration;
        } else {
          return this.appConsts.settings.HostSettings.UseCaptchaOnTenantRegistration;
        }
      },
      useCaptcha() {
        return this.abp.setting.getBoolean(
          this.appConsts.settings.HostSettings.UseCaptchaOnTenantRegistration,
        );
      },
    },
    watch: {
      'form.tenancyName': {
        handler(newval, _oldval) {
          if (newval === '' || newval === null) {
            return;
          }
          this.primaryKey = newval;
        },
      },
    },
    methods: {
      /** 返回登录页 */
      back(): void {
        this.$router.push('/account/login');
      },
      /** 验证码发生改变触发的事件 */
      getChange(val: string | undefined): void {
        this.form.verificationCode = val;
      },
      /** 保存 */
      save(e): void {
        e.preventDefault();
        (this.$refs.formRef as any).validate().then(() => {
          this.isSubmitting = true;
          this.tenantRegistrationServiceProxy
            .registerTenant(this.form)
            .finally(() => {
              this.isSubmitting = false;
              this.saving = false;
            })
            .then((result) => {
              this.notify.success(this.l('SavedSuccessfully'));
              abp.multiTenancy.setTenantIdCookie(result.tenantId);
              // 租户默认激活，并且登陆没有使用验证码，自动登陆
              if (result.isActive && !result.useCaptchaOnUserLogin) {
                this.saving = true;
                this.loginService.authenticateModel.userNameOrEmailAddress =
                  this.form.adminEmailAddress;
                this.loginService.authenticateModel.password = this.form.tenantAdminPassword!;
                this.loginService.authenticate(
                  () => {},
                  () => {
                    if (this.$refs.captcha) {
                      (this.$refs.captcha as any).clearImg();
                    }
                  },
                  () => {
                    this.isSubmitting = false;
                  },
                );
              } else {
                this.back();
              }
            });
        });
      },

      userNameOrEmailAddressOnBlur(): void {
        this.tmpPrimaryKey = this.form.tenancyName;
      },
    },
  });
</script>

<style lang="less" scoped>
  @import './tenant-register.less';
</style>
